<template>
  <div v-show="$route.name === 'process-update'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/process-list' }">肉码生产成本记录
    </el-breadcrumb-item>
      <el-breadcrumb-item>肉码生产成本计算</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域--订单数据修改 -->
    <el-card>
      <div style="margin-bottom: 20px;">肉码生产成本计算</div>
      <el-row :gutter="20">
        <!-- 原料区域 -->
        <el-col :span="11">
          <el-card>
            <!-- 搜索与添加区域 -->
            <span style="margin-bottom: 20px;margin-right: 20px;">原料</span>
            <el-button type="success" @click="showMaterialAddDialog()">新增</el-button>
            <!-- 原料列表区域 -->
            <el-table :data="materialList" border stripe height="520" :summary-method="materialSummaries" :show-summary="groupid === 0 ? true : false" ref="table">
              <el-table-column label="分类" align="center" min-width="70" prop="category"></el-table-column>
              <el-table-column label="原料名称" align="center" min-width="100" prop="goods"></el-table-column>
              <el-table-column label="单位" align="center" min-width="50" prop="unit"></el-table-column>
              <el-table-column label="成本" align="center" min-width="80" prop="cost" v-if="groupid === 0"></el-table-column>
              <el-table-column label="数量" align="center" min-width="60" prop="count"></el-table-column>
              <el-table-column label="总成本" align="center" min-width="90" prop="total" v-if="groupid === 0"></el-table-column>
              <el-table-column label="操作" align="center" width="60">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <div style="margin-bottom: 5px;">
                    <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="showMaterialEditDialog(scope.row, scope.$index)"></el-button>
                    </el-tooltip>
                  </div>
                  <!-- 删除按钮 -->
                  <div>
                    <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteMaterial(scope.row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <!-- 成品数据 -->
        <el-col :span="13">
          <el-card>
            <!-- 搜索与添加区域 -->
            <span style="margin-bottom: 20px;margin-right: 20px;">肉码</span>
            <el-button type="success" @click="showProductAddDialog()">新增</el-button>
            <!-- 成品列表区域 -->
            <el-table :data="productList" border stripe height="520" :summary-method="productSummaries" :show-summary="groupid === 0 ? true : false" ref="table2">
              <el-table-column label="分类" align="center" min-width="70" prop="category"></el-table-column>
              <el-table-column label="肉码名称" align="center" min-width="100" prop="goods"></el-table-column>
              <el-table-column label="单位" align="center" min-width="50" prop="unit_in"></el-table-column>
              <el-table-column label="数量" align="center" min-width="60" prop="count"></el-table-column>
              <el-table-column label="实际成本" align="center" min-width="80" prop="cost" v-if="groupid === 0">
                <template slot-scope="scope">
                  <span :class="scope.row.cost === '待保存' ? 'red' : ''">{{scope.row.cost}}</span>
                </template>
              </el-table-column>
              <el-table-column label="实际总成本" align="center" min-width="90" prop="total_cost" v-if="groupid === 0">
                <template slot-scope="scope">
                  <span :class="scope.row.total_cost === '待保存' ? 'red' : ''">{{scope.row.total_cost}}</span>
                </template>
              </el-table-column>
              <el-table-column label="参考成本" align="center" min-width="80" prop="price_in" v-if="groupid === 0"></el-table-column>
              <el-table-column label="总参考成本" align="center" min-width="90" prop="total" v-if="groupid === 0"></el-table-column>
              <el-table-column label="操作" align="center" width="60">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <div style="margin-bottom: 5px;">
                    <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="showProductEditDialog(scope.row, scope.$index)"></el-button>
                    </el-tooltip>
                  </div>
                  <!-- 删除按钮 -->
                  <div>
                    <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteProduct(scope.row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-button  @click="back" style="margin-top: 20px;">返回</el-button>
          <el-button type="warning" @click="saveSubmit" style="margin-top: 20px;">重新计算并保存</el-button>
          <el-button type="primary" @click="handleSubmit" style="margin-top: 20px;">提交</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 保存原料对话框 -->
    <el-dialog :title="isMaterialAdd ? '新增原料' : '修改原料'" :visible.sync="saveMaterialDialogVisible" width="70%" @close="saveMaterialDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="saveMaterialForm" :rules="saveMaterialFormRules" ref="saveMaterialFormRef" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="category_id">
              <el-select v-model="saveMaterialForm.category_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择品类">
                <el-option v-for="item in materialCategoryList" :label="item.category_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.category_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原料" prop="goods_id">
              <el-select v-model="saveMaterialForm.goods_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择原料">
                <el-option v-for="item in materialGoodsList" :label="item.name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="saveMaterialForm.unit" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位成本" prop="cost" v-if="groupid === 0">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveMaterialForm.cost" style="width:200px" disabled></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="count">
              <el-input-number controls-position="right" :precision="2" :step="1" :min="0.01" :max="parseFloat(saveMaterialForm.house_count)" v-model="saveMaterialForm.count" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总成本" prop="total" v-if="groupid === 0">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveMaterialForm.total" style="width:200px" disabled></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveMaterialDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMaterial">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 保存肉码对话框 -->
    <el-dialog :title="isProductAdd ? '新增肉码' : '修改肉码'" :visible.sync="saveProductDialogVisible" width="70%" @close="saveProductDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="saveProductForm" :rules="saveProductFormRules" ref="saveProductFormRef" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="category_id">
              <el-select v-model="saveProductForm.category_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择品类">
                <el-option v-for="item in productCategoryList" :label="item.category_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.category_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="肉码" prop="goods_id">
              <el-select v-model="saveProductForm.goods_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择肉码">
                <el-option v-for="item in productGoodsList" :label="item.name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit_in">
              <el-input v-model="saveProductForm.unit_in" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="参考成本" prop="price_in" v-if="groupid === 0">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveProductForm.price_in" style="width:200px" disabled></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="count">
              <el-input-number controls-position="right" :precision="2" :step="1" :min="0.01" v-model="saveProductForm.count" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总成本" prop="total" v-if="groupid === 0">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveProductForm.total" style="width:200px" disabled></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveProductDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      groupid: '',
      process_time: '',
      // ===== 原料模块 =====
      // 原料分类列表
      materialCategoryList: [],
      materialGoodsList: [],
      // 原料表格
      materialList: [],
      // 是否新增
      isMaterialAdd: true,
      saveMaterialDialogVisible: false,
      modifyMaterialIndex: 0,
      materialIsSet: 0,
      // 添加新的原料
      saveMaterialForm: {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        cost: 0.00,
        unit: '',
        count: 1,
        house_count: 1,
        total: 0.00
      },
      // 添加表单的验证规则对象
      saveMaterialFormRules: {
        category_id: [
          { required: true, type: 'number', message: '请选择分类', trigger: 'change' }
        ],
        goods_id: [
          { type: 'number', required: true, message: '请选择商品', trigger: 'change' }
        ],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      // ===== 肉码模块 =====
      // 肉码分类列表
      productCategoryList: [],
      productGoodsList: [],
      // 肉码表格
      productList: [],
      // 是否新增
      isProductAdd: true,
      saveProductDialogVisible: false, 
      modifyProductIndex: 0,
      productIsSet: 0,
      saveProductForm: {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        price_in: 0.00,
        unit_in: '',
        count: 1,
        cost: 0.00,
        total: 0.00,
        total_cost: 0.00
      },
      // 添加表单的验证规则对象
      saveProductFormRules: {
        category_id: [
          { required: true, type: 'number', message: '请选择分类', trigger: 'change' }
        ],
        goods_id: [
          { type: 'number', required: true, message: '请选择商品', trigger: 'change' }
        ],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getUserInfo()
    this.getProcess()
    this.materialGetCategoryList()
    this.productGetCategoryList()
  },
  watch: {
    'saveMaterialForm.category_id': {
      handler: function(val, oldval) {
        if (val) {
          this.saveMaterialForm.category = this.materialCategoryList.find((item) => {
            return item.id === val
          }).category_name
          this.materialGetGoodsList(val)
        } else {
          this.saveMaterialForm.category = ''
          this.materialGoodsList = []
          this.saveMaterialForm.goods_id = ''
          this.saveMaterialForm.count = 1
        }
      }
    },
    'saveMaterialForm.goods_id': {
      handler: function(val, oldval) {
        if (val) {
          let goodsDetail = {}
          goodsDetail = this.materialGoodsList.find((item) => {
            return item.id === val
          })
          if (goodsDetail) {
            this.saveMaterialForm.goods = goodsDetail.name
            this.saveMaterialForm.unit = goodsDetail.unit
            this.saveMaterialForm.cost = goodsDetail.cost
            this.saveMaterialForm.count = 1
            this.saveMaterialForm.house_count = goodsDetail.house_count
          }
        } else {
          this.saveMaterialForm.goods = ''
          this.saveMaterialForm.unit = ''
          this.saveMaterialForm.cost = 0.00
          this.saveMaterialForm.count = 1
          this.saveMaterialForm.house_count = 1
        }
      }
    },
    'saveMaterialForm.count': {
      handler: function(val, oldval) {
        this.saveMaterialForm.total = val * this.saveMaterialForm.cost
      }
    },
    'saveMaterialForm.cost': {
      handler: function(val, oldval) {
        this.saveMaterialForm.total = val * this.saveMaterialForm.count
      }
    },
    'saveProductForm.category_id': {
      handler: function(val, oldval) {
        if (val) {
          this.saveProductForm.category = this.productCategoryList.find((item) => {
            return item.id === val
          }).category_name
          this.productGetGoodsList(val)
        } else {
          this.saveProductForm.category = ''
          this.productGoodsList = []
          this.saveProductForm.goods_id = ''
          this.saveProductForm.count = 1
        }
      }
    },
    'saveProductForm.goods_id': {
      handler: function(val, oldval) {
        if (val) {
          let goodsDetail = {}
          goodsDetail = this.productGoodsList.find((item) => {
            return item.id === val
          })
          if (goodsDetail) {
            this.saveProductForm.goods = goodsDetail.name
            this.saveProductForm.unit_in = goodsDetail.unit_in
            this.saveProductForm.price_in = goodsDetail.price_in
            this.saveProductForm.count = 1
          }
        } else {
          this.saveProductForm.goods = ''
          this.saveProductForm.unit_in = ''
          this.saveProductForm.price_in = 0.00
          this.saveProductForm.count = 1
        }
      }
    },
    'saveProductForm.count': {
      handler: function(val, oldval) {
        this.saveProductForm.total = val * this.saveProductForm.price_in
      }
    },
    'saveProductForm.price_in': {
      handler: function(val, oldval) {
        this.saveProductForm.total = val * this.saveProductForm.count
      }
    },
  },
  updated() {
    var _self = this
    this.$nextTick(() => {
      _self.$refs.table.doLayout()
      _self.$refs.table2.doLayout()
    })
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const { data: result } = await this.$http.get('/user/' + localStorage.userid)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.groupid = result.data.groupid === '' ? '' : result.data.groupid * 1
    },
    // 返回
    back () {
      localStorage.removeItem('ProcessTime')
      this.$router.push({ 'name': 'process-list' })
    },
    // 保存
    async saveSubmit() {
      if (!this.process_time) {
        return this.$message.error('提交失败，请检测日期')
      }
      // 循环验证原料
      const handleMaterial = []
      let checkMaterial = []
      let flagMaterial = 1
      this.materialList.forEach(melement => {
        if (!melement.goods_id || !melement.count || melement.cost.length === 0) {
          return this.$message.error('提交失败，请检测成品数据必填项')
        }
        if (checkMaterial.indexOf(melement.goods_id) !== -1) {
          flagMaterial = 0
          return false
        }
        checkMaterial.push(melement.goods_id)
        handleMaterial.push({
          goods_id: melement.goods_id,
          count: melement.count ? melement.count : 0,
          cost: melement.cost ? melement.cost : 0,
        })
      })
      // 循环验证成品
      const handleProduct = []
      let checkProduct = []
      let flagProduct = 1
      this.productList.forEach(pelement => {
        if (!pelement.goods_id || !pelement.count) {
          return this.$message.error('提交失败，请检测成品数据必填项')
        }
        if (checkProduct.indexOf(pelement.goods_id) !== -1) {
          flagProduct = 0
          return false
        }
        checkProduct.push(pelement.goods_id)
        handleProduct.push({
          goods_id: pelement.goods_id,
          count: pelement.count ? pelement.count : 0
        })
      })
      if (flagMaterial && flagProduct) {
        const { data: result } = await this.$http.post('/process', {
          material: handleMaterial, 
          product: handleProduct,
          processTime: this.process_time
        })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.$message.success('保存成功！')
        this.productList = result.data
      } else {
        return this.$message.error('数据重复')
      }
    },
    async handleSubmit() {
      // 弹框询问用户是否提交数据
      const confirmResult = await this.$confirm('是否确定提交？<br>提交后，正式进行肉码入库操作，本表单将不可更改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认提交，则返回值为字符串 confirm
      // 如果用户取消了提交，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return
      }
      // 循环验证原料
      const handleMaterial = []
      let checkMaterial = []
      let flagMaterial = 1
      if (!this.process_time) {
        return this.$message.error('提交失败，请检测日期')
      }
      this.materialList.forEach(melement => {
        if (!melement.goods_id || !melement.count || melement.cost.length === 0) {
          return this.$message.error('提交失败，请检测成品数据必填项')
        }
        if (checkMaterial.indexOf(melement.goods_id) !== -1) {
          flagMaterial = 0
          return false
        }
        checkMaterial.push(melement.goods_id)
        handleMaterial.push({
          goods_id: melement.goods_id,
          count: melement.count ? melement.count : 0,
          cost: melement.cost ? melement.cost : 0,
        })
      })
      // 循环验证成品
      const handleProduct = []
      let checkProduct = []
      let flagProduct = 1
      this.productList.forEach(pelement => {
        if (!pelement.goods_id || !pelement.count) {
          return this.$message.error('提交失败，请检测成品数据必填项')
        }
        if (checkProduct.indexOf(pelement.goods_id) !== -1) {
          flagProduct = 0
          return false
        }
        checkProduct.push(pelement.goods_id)
        handleProduct.push({
          goods_id: pelement.goods_id,
          count: pelement.count ? pelement.count : 0
        })
      })
      if (flagMaterial && flagProduct) {
        const { data: result } = await this.$http.post('/process/handle', {
          material: handleMaterial, 
          product: handleProduct,
          processTime: this.process_time
        })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.$message.success('提交成功！')
        this.$router.push({ path: '/process-list' })
      } else {
        return this.$message.error('数据重复')
      }
    },
    // 获取当日数据
    getProcess() {
      this.process_time = this.$route.params.process_time
      if (this.$route.params.process_time) {
        this.process_time = this.$route.params.process_time
        localStorage.setItem('ProcessTime', this.$route.params.process_time)
      } else {
        this.process_time = localStorage.getItem('ProcessTime')
      }
      if (this.process_time) {
        // 获取当日详情数据
        this.getProcessData()
      }
    },
    // 获取当日详情数据
    async getProcessData() {
      const myDate = new Date(this.process_time)
      const year = myDate.getFullYear() // 获取当前年份
      const month = myDate.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
      const day = myDate.getDate() // 获取当前日（1-31）
      // 日期格式：2019/07/29 - 2019/07/29
      const { data: result } = await this.$http.get('/process/detail', { params: {processTime:  `${year}-${month}-${day}`} })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.materialList = result.data.materialList
      this.productList = result.data.productList
    },
    // ====== 原料区域 ======
    // 获取原料分类
    async materialGetCategoryList() {
      const { data: result } = await this.$http.get('/category', {params: { process: 0, 'isHouse': 1 }})
      if (result.status !== 200) return this.$message.error(result.msg)
      this.materialCategoryList = result.data
    },
    // 获取原料产品
    async materialGetGoodsList(category_id) {
      const params = {
        page: 1,
        pageSize: 100000,
        category_id: category_id,
        process: 0,
        isHouse: 1
      }
      const { data: result } = await this.$http.get('/goods/list', { params: params })
      if (result.status === 200) {
        this.materialGoodsList = result.data
        if (this.materialIsSet) {
          this.saveMaterialForm.goods_id = ''
          this.saveMaterialForm.count = 1
        }
      }
    },
    // 显示原料对话框
    showMaterialAddDialog() {
      this.isMaterialAdd = true
      this.saveMaterialForm = {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        cost: 0.00,
        unit: '',
        count: 1,
        house_count: 1,
        total: 0.00
      }
      this.saveMaterialDialogVisible = true
      this.materialIsSet = 1
    },
    // 监听新增原料对话框的关闭事件
    saveMaterialDialogClosed() {
      this.materialIsSet = 0
      if (this.isMaterialAdd) {
        this.$refs.saveMaterialFormRef.resetFields()
      }
    },
    // 显示修改原料对话框
    showMaterialEditDialog(contact, index) {
      this.isMaterialAdd = false
      this.saveMaterialForm = this.$_.cloneDeep(contact)
      this.modifyMaterialIndex = index
      this.saveMaterialDialogVisible = true
    },
    // 删除原料
    async deleteMaterial(material) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该原料，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      this.materialList.splice(
        this.materialList.findIndex((existedmaterial) => existedmaterial === material),
        1
      )
      this.$message.success('删除原料成功！')
    },
    // 原料总成本合计
    materialSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index !== 5) {
          sums[index] = ''
          return
        }
        else {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            var aa = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0)
            sums[index] = parseFloat(aa).toFixed(2)
          } else {
            sums[index] = '';
          }
        }
      })
      return sums
    },
    // 点击按钮，添加原料
    saveMaterial() {
      this.$refs.saveMaterialFormRef.validate(async (valid) => {
        if (!valid) return
        var material = this.$_.cloneDeep(this.saveMaterialForm)
        // 修改
        if (!this.isMaterialAdd) {
          this.materialList.splice(this.modifyMaterialIndex, 1, material)
          this.$message.success('修改原料成功！')
        } else {
          // 新增
          this.materialList.push(material)
          this.$message.success('添加原料成功！')
        }
        // 隐藏添加原料的对话框
        this.materialIsSet = 0
        this.saveMaterialDialogVisible = false
      })
    },
    // ====== 肉码区域 ======
    // 获取成品分类
    async productGetCategoryList() {
      const { data: result } = await this.$http.get('/category', {params: { process: 1 }})
      if (result.status !== 200) return this.$message.error(result.msg)
      this.productCategoryList = result.data
    },
    // 获取成品产品
    async productGetGoodsList(category_id) {
      const params = {
        page: 1,
        pageSize: 100000,
        category_id: category_id,
        process: 1
      }
      const { data: result } = await this.$http.get('/goods/list', { params: params })
      if (result.status === 200) {
        this.productGoodsList = result.data
        if (this.productIsSet) {
          this.saveProductForm.goods_id = ''
          this.saveProductForm.count = 1
        }
      }
    },
    // 监听新增成品对话框的关闭事件
    saveProductDialogClosed() {
      this.productIsSet = 0
      if (this.isProductAdd) {
        this.$refs.saveProductFormRef.resetFields()
      }
    },
    // 显示成品对话框
    showProductAddDialog() {
      this.isProductAdd = true
      this.saveProductForm = {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        price_in: 0.00,
        unit_in: '',
        count: 1,
        cost: '待保存',
        total: 0.00,
        total_cost: '待保存'
      }
      this.saveProductDialogVisible = true
      this.productIsSet = 1
    },
    // 显示成品对话框
    showProductEditDialog(contact, index) {
      this.isProductAdd = false
      this.saveProductForm = this.$_.cloneDeep(contact)
      this.saveProductForm.cost = '待保存'
      this.saveProductForm.total_cost = '待保存'
      this.modifyProductIndex = index
      this.saveProductDialogVisible = true
    },
    // 删除肉码
    async deleteProduct(product) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该肉码，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      this.productList.splice(
        this.productList.findIndex((existedproduct) => existedproduct === product),
        1
      )
      this.$message.success('删除肉码成功！')
    },
    // 成品总成本合计
    productSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index !== 5 && index !== 7) {
          sums[index] = ''
          return
        }
        else {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            var aa = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0)
            sums[index] = parseFloat(aa).toFixed(2)
          } else {
            sums[index] = '';
          }
        }
      })
      return sums
    },
    // 点击按钮，添加成品
    saveProduct() {
      this.$refs.saveProductFormRef.validate(async (valid) => {
        if (!valid) return
        var product = this.$_.cloneDeep(this.saveProductForm)
        // 修改
        if (!this.isProductAdd) {
          this.productList.splice(this.modifyProductIndex, 1, product)
          this.$message.success('修改成品成功！')
        } else {
          // 新增
          this.productList.push(product)
          this.$message.success('添加成品成功！')
        }
        // 隐藏添加成品的对话框
        this.productIsSet = 0
        this.saveProductDialogVisible = false
      })
    }
  }
}
</script>

<style lang="less">
.red {
  color: red;
}
</style>

